package com.atguigu.edu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.edu.realtime.func.DimAsyncFunction;
import com.atguigu.edu.realtime.beans.TradProvinceOrderBean;
import com.atguigu.edu.realtime.utils.DateFormatUtil;
import com.atguigu.edu.realtime.utils.MyClickhouseUtil;
import com.atguigu.edu.realtime.utils.MyKafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.*;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;


public class DwsTradeProvinceOrderWindow {
    public static void main(String[] args) throws Exception {
        //基本环境准备
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //设置并行度
        env.setParallelism(4);
        //检查点相关设置
        //开启检查点
 /*       env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);
        //设置超时时间
        env.getCheckpointConfig().setCheckpointTimeout(60000L);
        //job取消之后，检查点是否保留
        env.getCheckpointConfig().enableExternalizedCheckpoints(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
        //设置两个检查点之间的最小时间间隔
       env.getCheckpointConfig().setMinPauseBetweenCheckpoints(2000L);
       //设置重启策略
        env.setRestartStrategy(RestartStrategies.failureRateRestart(3, Time.days(30), Time.seconds(3)));
        //状态后端
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop101:8020/edu/ck");
        //操作hadoop用户
        System.setProperty("HADOOP_USER_NAME","atguigu");*/
        //从kafka事实表读数据
        String topic = "dwd_trade_order_detail";
        String groupId = "dws_trade_province_group";

        //jsonObjDS.print();
// {"coupon_amount":"0.0","course_id":"273","od_ts":"1668839853","course_name":"尚硅谷大数据技术之Shell","session_id":"598cf30d-dafd-485d-aec4-e2f4c1a6f912","origin_amount":"200.0","user_id":"2647","province_id":"19","row_op_ts":"2022-11-19 06:37:32.637Z","final_amount":"200.0","id":"86298","order_id":"75428"}

        DataStreamSource<String> kafkaStrDS = env.addSource(MyKafkaUtil.getKafkaConsumer(topic, groupId));
        //转换成实体对象
        SingleOutputStreamOperator<TradProvinceOrderBean> orderBeanDS = kafkaStrDS.map(new MapFunction<String, TradProvinceOrderBean>() {
            @Override
            public TradProvinceOrderBean map(String jsonStr) throws Exception {
                JSONObject jsonObj = JSON.parseObject(jsonStr);

                TradProvinceOrderBean orderBean = TradProvinceOrderBean.builder()
                        .provinceId(jsonObj.getString("province_id"))
                        .orderIdSet(new ArrayList<>(Collections.singleton(jsonObj.getString("order_id"))))
                        .userIdSet(new HashSet<>(Collections.singleton(jsonObj.getString("user_id"))))
                        .orderAmount(jsonObj.getDouble("final_amount"))
                        .ts(jsonObj.getLong("od_ts") * 1000)
                        .build();
                return orderBean;
            }
        }
        );
//orderBeanDS.print();

//指定waterMark 提取事件时间字段
        SingleOutputStreamOperator<TradProvinceOrderBean> waterMarkDS = orderBeanDS.assignTimestampsAndWatermarks(WatermarkStrategy.<TradProvinceOrderBean>forBoundedOutOfOrderness(Duration.ofSeconds(3)).withTimestampAssigner(
                new SerializableTimestampAssigner<TradProvinceOrderBean>() {
                    @Override
                    public long extractTimestamp(TradProvinceOrderBean tradProvinceOrderBean, long l) {
                        return tradProvinceOrderBean.getTs();
                    }
                }
        ));
        //按照省份Id 分组
        KeyedStream<TradProvinceOrderBean, String> keyedDS = waterMarkDS.keyBy(r -> r.getProvinceId());
        //开窗
        WindowedStream<TradProvinceOrderBean, String, TimeWindow> windowDS = keyedDS.window(TumblingEventTimeWindows.of(Time.seconds(10)));
        //聚合计算
        SingleOutputStreamOperator<TradProvinceOrderBean> reduceDS = windowDS.reduce(new ReduceFunction<TradProvinceOrderBean>() {
            @Override
            public TradProvinceOrderBean reduce(TradProvinceOrderBean v1, TradProvinceOrderBean v2) throws Exception {
                v1.getOrderIdSet().addAll(v2.getOrderIdSet());
                v1.getUserIdSet().addAll(v2.getUserIdSet());
                v1.setOrderAmount(v1.getOrderAmount() + v2.getOrderAmount());
                return v1;
            }
            },
                new WindowFunction<TradProvinceOrderBean, TradProvinceOrderBean, String, TimeWindow>() {
                    @Override
                    public void apply(String s, TimeWindow timeWindow, Iterable<TradProvinceOrderBean> iterable, Collector<TradProvinceOrderBean> collector) throws Exception {
                        String stt = DateFormatUtil.toYmdHms(timeWindow.getStart());
                        String edt = DateFormatUtil.toYmdHms(timeWindow.getEnd());
                        for (TradProvinceOrderBean tradProvinceOrderBean : iterable) {
                            tradProvinceOrderBean.setStt(stt);
                            tradProvinceOrderBean.setEdt(edt);
                            tradProvinceOrderBean.setTs(System.currentTimeMillis());
                            tradProvinceOrderBean.setOrderCount((long) tradProvinceOrderBean.getOrderIdSet().size());
                            tradProvinceOrderBean.setUserCount((long) tradProvinceOrderBean.getUserIdSet().size());
                            collector.collect(tradProvinceOrderBean);

                        }
                    }
                });

     //  reduceDS.print();
      //和省份维度进行关联
        SingleOutputStreamOperator<TradProvinceOrderBean> WithProvinceDS = AsyncDataStream.unorderedWait(
                reduceDS,
                new DimAsyncFunction<TradProvinceOrderBean>("dim_base_province") {


                    @Override
                    public void join(JSONObject dimInfoJsonObj, TradProvinceOrderBean orderBean) {
                        orderBean.setProvinceName(dimInfoJsonObj.getString("NAME"));
                    }

                    @Override
                    public String getKey(TradProvinceOrderBean orderBean) {
                        return orderBean.getProvinceId();
                    }
                },
                60, TimeUnit.SECONDS

        );
WithProvinceDS.print();
//写到clickhouse
        WithProvinceDS.addSink(
                MyClickhouseUtil.getSinkFunction("insert into dws_trade_province_order_window values(?,?,?,?,?,?,?,?)")
        );
        env.execute();

    }
}
